package com.thwj.common.utils.http;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author: 可乐
 * @date: 2023/01/20 13:49
 * <p>
 */
public class OkHttpClientHelper {

    private OkHttpClient okHttpClient;

    private ConnectionPool pool = new ConnectionPool(6, 10, TimeUnit.MINUTES);

    private OkHttpClientHelper() {
    }

    public static OkHttpClientHelper build() {
        OkHttpClientHelper okHttpHelper = new OkHttpClientHelper();
        okHttpHelper.init();
        return okHttpHelper;
    }

    private void init() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.MINUTES)
                .followRedirects(true)
                .readTimeout(10, TimeUnit.MINUTES)
                .retryOnConnectionFailure(true)
                .writeTimeout(10, TimeUnit.MINUTES).connectionPool(pool)
                .build();
    }

    public void destroy() {

        if (okHttpClient != null) {
            ConnectionPool connectionPool = okHttpClient.connectionPool();
            connectionPool.evictAll();
            ExecutorService executorService = okHttpClient.dispatcher().executorService();
            executorService.shutdown();
            try {
                executorService.awaitTermination(3, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
            }
        }
    }

    public OkHttpClient getClient() {
        return okHttpClient;
    }

}
